import React, {PureComponent} from 'react'
import 'antd/dist/antd.css'
import './styles.css'
import rules from '../../utils/rules'
import XLSX from 'xlsx'
import {Button, message, PageHeader, Table, Upload} from 'antd'
import {InboxOutlined, QuestionOutlined} from '@ant-design/icons'
import {ShakeLittle} from 'reshake'

const {Dragger} = Upload

const idColumns = [
    {
        title: '文件名',
        dataIndex: 'name',
        key: 'name',
        width: 200,
    },
    {
        title: '身份证号',
        dataIndex: 'id',
        key: 'id',
    },
]
const phoneColumns = [
    {
        title: '文件名',
        dataIndex: 'name',
        key: 'name',
        width: 200,
    },
    {
        title: '联系方式',
        dataIndex: 'phone',
        key: 'phone',
    },
]

const filesColumns = [{
    title: '文件名',
    dataIndex: 'name',
    key: 'name',
    width: 200,
}, {
    title: '点击下方按钮进行数据检索',
    dataIndex: 'date',
    key: 'date'
}]

export default class Index extends PureComponent {

    state = {
        cells: [],
        idList: [],
        phoneList: [],
        loaded: false,
        files: [],
        actType: undefined,
    }
    handleFile = (info) => {
        console.log('🚗 文件处理', info.file)
        const {status, name, lastModified} = info.file
        clearTimeout(this.uploadTimer)
        if (!name.match(/xls/)) { /*文件类型限制*/
            message.error('目前仅支持Excel文件')
            return
        }
        if (status === 'uploading') {
            this.setState({loaded: false})
        }
        if (status === 'done') {
            const reader = new FileReader()
            reader.onload = (file) => {
                const data = new Uint8Array(file.target.result)
                const workbook = XLSX.read(data, {type: 'array'})
                // const cells = this.handleCell(workbook.Strings)
                const cells = this.handleSheet(workbook.Sheets)
                // 拆分数据
                const ids = this.matchRules(rules.id, cells)
                const phones = this.matchRules(rules.phone, cells)
                console.log('🚗 检索手机号', phones)
                const date = new Date(lastModified)
                const idDataSource = this.state.idList.concat(this.toDataSource(ids, name, date, 'id'))
                const phoneDataSource = this.state.phoneList.concat(this.toDataSource(phones, name, date, 'phone'))
                const fileDataSource = this.state.files.concat([{name, date}])
                console.log(fileDataSource)
                this.setState({files: fileDataSource, idList: idDataSource, phoneList: phoneDataSource})
                if (info.fileList.every(file => file.status === 'done')) {
                    this.uploadTimer = setTimeout(() => {
                        this.setState({loaded: true})
                    }, 1000)
                }
            }
            reader.readAsArrayBuffer(info.file.originFileObj)
        } else if (status === 'error') {
            message.error(`${info.file.name} 上传失败`)
        }
    }

    handleCell = (list) => {
        console.log('获取单元格', list)
        return list.map(item => item.h)
    }
    handleSheet = (sheet) => {
        const cellBox = []
        const sheets = Object.values(sheet)
        for (let i = 0; i < sheets.length; i++) {
            const sh = sheets[i]
            const cells = Object.values(sh)
            for (let j = 0; j < cells.length; j++) {
                const cell = cells[j]
                if (typeof cell === 'object' && cell.v) cellBox.push(cell.v)
            }
        }
        return cellBox
    }
    matchRules = (rule, cells) => {
        console.log(rule, cells)
        return cells.filter(cell => rule.test(cell))
    }

    toDataSource = (cells, name, date, type) => cells.map(cell => {
        return {
            name,
            date,
            [type]: cell
        }
    })
    clearList = () => {
        this.setState({idList: [], phoneList: [], files: [], loaded: false})
    }
    dateFormat = (date) => {
        return new Date(date)
    }
    switchType = (type) => {
        this.setState({actType: type})
    }
    save = () => {
        const {actType, idList, phoneList} = this.state
        const workbook = XLSX.utils.book_new()
        const ws_name = "Sheet1"
        let cows = [], header = []
        if (actType === 'id' && idList) {
            cows = this.state.idList.map(item => [item.name.split('.')[0], item.id])
            header = ["文件名", "身份证号"]
        } else if (actType === 'phone' && phoneList) {
            cows = this.state.phoneList.map(item => [item.name.split('.')[0], item.phone.toString()])
            header = ["文件名", "联系方式"]
        }
        const ws_data = [header].concat(cows)
        console.log('🔪 导出的数据', ws_data)
        if (ws_data.length < 1) {
            message.warn('未找到指定数据')
            return
        }
        const ws = XLSX.utils.aoa_to_sheet(ws_data)
        XLSX.utils.book_append_sheet(workbook, ws, ws_name)
        XLSX.writeFile(workbook, 'out.xlsx')
    }
    phonePass = () => {
        const phones = JSON.parse(JSON.stringify(this.state.phoneList))
        for (let i = 0; i < phones.length; i++) {
            const oldPhone = phones[i].phone.toString()
            phones[i].phone = oldPhone.substr(0, 4) + '***' + oldPhone.substr(7)
        }
        this.setState({phoneList: phones})
    }
    idPass = () => {
        const ids = JSON.parse(JSON.stringify(this.state.idList))
        for (let i = 0; i < ids.length; i++) {
            const oldId = ids[i].id
            ids[i].id = oldId.substr(0, 6) + '********' + oldId.substr(14)
        }
        this.setState({idList: ids})
    }
    help = () => {
        window.open('https://browniu-wx-1257187612.cos.ap-shanghai.myqcloud.com/%E7%90%AA%E7%9A%84%E5%8A%9E%E5%85%AC%E9%AD%94%E6%B3%95%E7%9B%92-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E.pdf', '_black')
    }
    dataPass = () => {
        const {actType} = this.state
        switch (actType) {
            case 'id':
                this.idPass()
                break
            case 'phone':
                this.phonePass()
                break
        }
    }

    render() {
        const {idList, loaded, files, phoneList, actType} = this.state
        return (
            <div className={'home'}>
                <header>
                    <PageHeader
                        className="site-page-header"
                        title="琪的办公魔法盒"
                        subTitle="批量处理表单文件的工具箱"
                    />
                    <div className="help" onClick={this.help}><QuestionOutlined style={{color: 'pink'}}/></div>
                </header>
                {!loaded && <div className={`upload`}>
                    <Dragger beforeUpload={(file) => {
                        if (!file.name.match(/xls|xlsx/)) message.warn('文件格式不')
                    }} directory={false} accept={'.xls,.xlsx'} onChange={this.handleFile} name={'file'} multiple={true}
                             action={'https://www.mocky.io/v2/5cc8019d300000980a055e76'}>
                        <p className="ant-upload-drag-icon">
                            <ShakeLittle>
                                <InboxOutlined style={{color: 'pink'}}/>
                            </ShakeLittle>
                        </p>
                        <p className="ant-upload-text">点击上传文件或者拖进来</p>
                    </Dragger>
                </div>}
                {loaded && <div className="panel">
                    <div className="files">
                        {!actType && <Table dataSource={files} columns={filesColumns} pagination={false}/>}
                        {actType === 'id' && <Table dataSource={idList} columns={idColumns} pagination={false}/>}
                        {actType === 'phone' &&
                        <Table dataSource={phoneList} columns={phoneColumns} pagination={false}/>}
                    </div>
                    <div className="control">
                        <Button type={'primary'} onClick={this.save}>导出表格</Button>
                        <Button onClick={this.clearList}>清空数据</Button>
                        <Button onClick={() => this.switchType('id')}>检索身份证</Button>
                        <Button onClick={() => this.switchType('phone')}>检索手机号</Button>
                        {actType && <Button onClick={this.dataPass}>隐私替换</Button>}
                    </div>
                </div>}
            </div>
        )
    }
}